﻿// -----------------------------------------------------------------------
// <copyright file="StringConvertUtil.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace NetFramework.Utility
{
    using System;
    using System.Security.Cryptography;
    using System.Text;
    using System.Text.RegularExpressions;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public static class StringUtil
    {
        #region 转16进制字符串
        /// <summary>
        /// Byte 数组值转16进制字符串
        /// </summary>
        /// <param name="b">输入参数：Byte value</param>
        /// <returns>16进制字符串</returns>
        public static String ByteArrayToHexString(Byte[] bytes)
        {
            StringBuilder temp = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                temp.Append(bytes[i].ToString("X2"));
            }
            return temp.ToString();
        }

        /// <summary>
        /// Byte 值转16进制字符串
        /// </summary>
        /// <param name="b">输入参数：Byte value</param>
        /// <returns>16进制字符串</returns>
        public static String ByteToHexString(Byte b)
        {
            return b.ToString("X2");
        }

        /// <summary>
        /// Converts a hex string to a byte array
        /// </summary>
        /// <param name="hexString">The hex string to convert</param>
        /// <returns>A byte array representing the hex string</returns>
        public static byte[] HexStringToByteArray(string hexString)
        {
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
        #endregion

        #region 获取指定长度的随机 Byte Array
        /// <summary>
        /// 获取指定长度的随机 Byte Array
        /// </summary>
        /// <param name="count">返回的Byte Array 长度</param>
        /// <returns>返回指定长度的 Byte Array</returns>
        public static byte[] GetRandomBytes(int count)
        {
            byte[] randomBytes = new byte[count];
            RNGCryptoServiceProvider gen = new RNGCryptoServiceProvider();
            gen.GetBytes(randomBytes);
            return randomBytes;
        }
        #endregion

        #region 日期与Byte互转
        /// <summary>
        /// Convert a DateTime to the equivalent long (Win32 FileTime) byte array
        /// </summary>
        /// <param name="date">DateTime to convert</param>
        /// <returns>"long" byte array representing the DateTime</returns>
        public static byte[] DateToByteArray(DateTime date)
        {
            long longDate = date.ToFileTime();
            return BitConverter.GetBytes(longDate);
        }
        /// <summary>
        /// Coverts a long (aka Win32 FileTime) byte array to a DateTime
        /// </summary>
        /// <param name="bytes">Bytes to convert</param>
        /// <returns>DateTime representation of the "long" bytes</returns>
        public static DateTime ByteArrayToDate(byte[] bytes)
        {
            if (bytes.Length != 8)
                throw new ArgumentException("bytes");
            long longDate = BitConverter.ToInt64(bytes, 0);
            return DateTime.FromFileTime(longDate);
        }
        #endregion

        #region IP转换
        #endregion

        #region 全角数字转换为数字
        /// <summary>
        /// 将全角数字转换为数字
        /// </summary>
        /// <param name="SBCCase"></param>
        /// <returns></returns>
        public static string SBCCaseToNumberic(string SBCCase)
        {
            char[] c = SBCCase.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
                if (b.Length == 2)
                {
                    if (b[1] == 255)
                    {
                        b[0] = (byte)(b[0] + 32);
                        b[1] = 0;
                        c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
                    }
                }
            }
            return new string(c);
        }
        #endregion

        #region 获取中文长度
        /// <summary>
        /// 获取 gb2312 字符串长度
        /// </summary>
        /// <param name="content">字符串,兼容Null和DbNull.Value</param>
        /// <param name="length">长度</param>
        /// <returns></returns>
        public static string GetGB2312StringLength(object obj, int length)
        {
            return GetStringLength(obj, length, "gb2312");
        }

        /// <summary>
        /// 获取 gb2312 字符串长度
        /// </summary>
        /// <param name="content">字符串,兼容Null和DbNull.Value</param>
        /// <param name="length">长度</param>
        /// <returns></returns>
        public static string GetGB2312StringLength(object obj, int length, string suffix)
        {
            return GetStringLength(obj, length, "gb2312", suffix);
        }

        /// <summary>
        /// 获取字符串长度
        /// </summary>
        /// <param name="content">字符串,兼容Null和DbNull.Value</param>
        /// <param name="length">长度</param>
        /// <param name="encode">编码</param>
        /// <returns></returns>
        public static string GetStringLength(object obj, int length, string encode)
        {
            return GetStringLength(obj, length, encode, null);
        }

        /// <summary>
        /// 获取字符串长度
        /// </summary>
        /// <param name="content">字符串,兼容Null和DbNull.Value</param>
        /// <param name="length">长度</param>
        /// <param name="encode">编码</param>
        /// <returns></returns>
        public static string GetStringLength(object obj, int length, string encode, string suffix)
        {
            if (obj == null || obj == DBNull.Value) return string.Empty;
            string content = obj.ToString();

            string tmp = null;
            if (!string.IsNullOrEmpty(suffix))
                tmp = content;

            Encoding encoding = Encoding.GetEncoding(encode);
            StringBuilder sb = new StringBuilder();
            int totalLength = 0;
            foreach (char contentChar in content)
            {
                int size = encoding.GetByteCount(new char[] { contentChar });
                if (totalLength + size > length)
                {
                    break;
                }

                sb.Append(contentChar);
                totalLength += size;
            }

            string result = sb.ToString();
            if (!string.IsNullOrEmpty(suffix))
            {
                if (tmp != result)
                    result += suffix;
            }

            return result;
        }
        #endregion

        #region Remove HTML
        /// <summary>
        /// 删除HTML标记
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string RemoveHTML(string html)
        {
            string[] aryRegex ={@"<%=[\w\W]*?%>",    @"<script[\w\W]*?</script>",     @"<style[\w\W]*?</style>",   @"<[/]?[\w\W]*?>",   @"([\r\n])[\s]+",
                              @"&(nbsp|#160);",    @"&(iexcl|#161);",  @"&(cent|#162);",            @"&(pound|#163);",   @"&(copy|#169);",
                              @"&#(\d+);",         @"-->",                          @"<!--.*\n"};

            //(<\/?)(?i:(?<element>a(bbr|cronym|ddress|pplet|rea)?|b(ase(font)?|do|ig|lockquote|ody|r|utton)?|c(aption|enter|ite|(o(de|l(group)?)))|d(d|el|fn|i(r|v)|l|t)|em|f(ieldset|o(nt|rm)|rame(set)?)|h([1-6]|ead|r|tml)|i(frame|mg|n(put|s)|sindex)?|kbd|l(abel|egend|i(nk)?)|m(ap|e(nu|ta))|no(frames|script)|o(bject|l|pt(group|ion))|p(aram|re)?|q|s(amp|cript|elect|mall|pan|t(r(ike|ong)|yle)|u(b|p))|t(able|body|d|extarea|foot|h|itle|r|t)|u(l)?|var))(\s(?<attr>.+?))*> 
            string[] aryReplacment = { "", "", "", "", "", " ", "", "", "", "", "", "", "" };
            string strStripped = html;

            try
            {
                for (int i = 0; i < aryRegex.Length; i++)
                {
                    Regex regex = new Regex(aryRegex[i], RegexOptions.IgnoreCase);
                    strStripped = regex.Replace(strStripped, aryReplacment[i]);
                }
            }
            catch
            {
                return html;
            }

            //Replace "\r\n" to an empty character.
            strStripped.Replace("\r\n", "");
            strStripped.Replace("\t", "");

            return strStripped;
        }
        #endregion
    }
}
